//
//  SqliteInterface.m
//  CALayer
//
//  Created by Terry on 11-5-30.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SqliteInterface.h"
#import "FMDatabaseQueue.h"

@implementation SqliteInterface

@synthesize  db;
@synthesize dbRealPath;

//SqliteInterface *sharedSqliteInterface;

+ (SqliteInterface *) sharedSqliteInterface
{

    static SqliteInterface *sharedSqliteInterface = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSqliteInterface = [[SqliteInterface alloc] init];
    });
    
    return sharedSqliteInterface;
}


- (void) connectDB
{
	if (db == nil) {
		db = [[FMDatabase alloc] initWithPath:dbRealPath];
	}
	if (![db open]) {
		NSLog(@"Could not open database.");
	}else {
      
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//        NSInteger newDatabaseVersion =[[self getDatebaseVersionCode]integerValue];
//        NSInteger oldDatabaseVersion = [[defaults valueForKey:@"DatabaseVersion"] integerValue];
//        if (oldDatabaseVersion < newDatabaseVersion) {
//            BOOL success = [self upgradeDatabase:oldDatabaseVersion withNewVersion:newDatabaseVersion];
//            if (success) {
//                [defaults setValue:[NSNumber numberWithInteger: newDatabaseVersion] forKey:@"DatabaseVersion"];
//            }
//        }
//        [defaults synchronize];
		NSLog(@"DataBase has already opened");
	}
	
}
- (void) closeDB
{ 

	[db close];
}


- (void) setupDB:(NSString *)dbFileName
{
	if (!dbFileName) {
		return;
	}
    if (db) {
         [[SqliteInterface sharedSqliteInterface] closeDB]; //关闭数据库
    }
    dbRealPath = [LIBRARY_FOLDER stringByAppendingString:[NSString stringWithFormat:@"/%@",dbFileName]];
	if (![[NSFileManager defaultManager] fileExistsAtPath:dbRealPath]) {
        FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbRealPath];
        [queue inDatabase:^(FMDatabase *db1) {
            BOOL worked = [db1 executeUpdate:@"create table contact (id integer PRIMARY KEY,name text,login_name text, phone  text,mobilephone text,department_id integer, department_name text,office_num text,is_activity bool,position text,token text,password text,head_name text,name_pinyin text,head_url text,mark text)"];
            FMDBQuickCheck(worked);
            
            BOOL worked1 = [db1 executeUpdate:@"create table department (id integer PRIMARY KEY,name text,sort integer)"];
              FMDBQuickCheck(worked1);
            BOOL worked2 = [db1 executeUpdate:@"create table company (id integer PRIMARY KEY,name text,member_count integer)"];
              FMDBQuickCheck(worked2);
            BOOL worked3 = [db1 executeUpdate:@"create table notice (id integer PRIMARY KEY,title text,time double,category_id integer,content text)"];
            FMDBQuickCheck(worked3);
            
            BOOL worked4 = [db1 executeUpdate:@"create table Category (id integer PRIMARY KEY,name text,sort integer,news_count integer,ico text,image_ico text)"];
            FMDBQuickCheck(worked4);
            

//            worked = [db1 executeUpdate:@"insert into test contact (1,'a', 'b', '22', '33', '124')"];
//            FMDBQuickCheck(worked);
//
//            FMResultSet *rs = [db1 executeQuery:@"select * from test"];
//            FMDBQuickCheck([rs next]);
//            [rs close];
            
        }];
        [queue close];
	}

	NSLog(@"dbRealPath: %@",dbRealPath);
}


-(NSNumber *)getDatebaseVersionCode{
    NSString *versionCodePath = [[NSBundle mainBundle]pathForResource:@"VersionCode" ofType:@"plist"];
    NSDictionary *versionDic = [NSDictionary dictionaryWithContentsOfFile:versionCodePath];
    NSNumber *versionCode = [versionDic objectForKey:@"DatebaseVersion"];
    return versionCode;
}


//2014.07.18
-(BOOL)upgradeDatabase:(NSInteger)oldVersion withNewVersion:(NSInteger)newVersion{
    BOOL success = NO;
    //增加了表ResourceGroup(ID,name,course_id,material_ids)，课程表增加resource_ids
    BOOL result1 = [db executeUpdate:@"Create table if not exists ResourceGroup (ID text,name text,course_id text,material_ids text)"];
    success = result1;
    return success;

}



@end
